<?php
/**
 *
 */
namespace Yz\modules\Modules;

class Model_List
    extends \Yz\modules\Generic\Model_List
{

    /** Identify all modules installed in Yz/modules
     *
     *  @return Yz_Array[items]
     */
    public function listInstalledModules()
    {
        $item0 = $this->selectItem();
        $modules = array();
        $path = \YZ_LIB . 'Yz/modules';
        $moduleDir = dir($path);
        while (false !== ($entry = $moduleDir->read())) {
            if ('.' !== substr($entry,0,1)) {
                include_once($path.'/'.$entry.'/'.'Module.php');
                $item = clone $item0;
                $item->name = $entry;
                $class = "Yz\\modules\\{$entry}\\Module";
                $item->isWebModule = is_subclass_of($class,'Yz_Module_WebModule_Interface')
                    ? 1
                    : 0
                    ;
                $modules[$entry] = $item;
            }
        }
        ksort($modules, SORT_STRING);
        return new \Yz_Array($modules);
    }


    /** re-check installed modules and update the database
     *
     *  @return chainable
     */
    public function updateModulesList()
    {
        $list = $this->listInstalledModules();
        $modelx = $this->module->selectModel("Default");
        foreach ($list as $item) {
            try {
                $modelx->addItem($item);
            } catch (\Yz_Exception $ex) {
                debug($ex);
            }
        }
        return $this;
    }


    /** fetch the list of modules with WebModule interface from DB
     *
     *  @return Yz_Hash
     */
    public function fetchWebModulesList()
    {
        debug();

        $item = $this->selectItem();

        $action = $this->selectAction('SelectFilterList');
        $action
            ->assignFields($item->describe())
            ->applyFilter($action::FILTER_WEB_MODULES)
            ;

        if (0 === $action->execute()->count()) {
            return new \Yz_Hash();
        }

        $values = $action->fetch();

        return $this->assignValues($values,$item);
    }


}
